<script>
import { useRoute } from 'vue-router'
import axios from 'axios'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import WordCloud from "../component/WordCloud.vue"
import {computed} from "vue"
import VChart from "vue-echarts"
import {
  LineChart,
  PieChart,
  ScatterChart
} from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  DatasetComponent,
  VisualMapComponent,
  GridComponent,
  ToolboxComponent,
  TransformComponent
} from 'echarts/components'
import { NInfiniteScroll } from 'naive-ui'
use([
  DatasetComponent,
  TooltipComponent,
  ToolboxComponent,
  VisualMapComponent,
  GridComponent,
  TransformComponent,
  ScatterChart,
  CanvasRenderer,
  LineChart,
  TitleComponent,
  LegendComponent,
  PieChart,
])


export default {
  name: 'ProductDetail',
  data() {
    return {
      count : 6,
      comments : null,
      route: useRoute(),
      productId: computed(() => useRoute().query?.product_id),
      priceHistory: [],
      phoneInfo: null,
      evaluations: null,
      goodWords: [],
      badWords: [],
      linearPredict:[],
      combinedLinearData:[],
      combinedARIMAData:[],
      ARIMAPredict:[],
      historyPriceOption: {
        title: {
          text: '历史价格',
          left: 'left'
        },
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: []
        },
        yAxis: {
          type: 'value',
          min: 0,
          max: 10000,
        },
        dataZoom: [
          {
            type: 'inside',
            start: 0,
            end: 100
          },
          {
            start: 0,
            end:100
          }
        ],
        series: [
          {
            data: [],
            type: 'line'
          }
        ]
      },

      evaluationOption: {
        title: {
          text: '好中差评占比',
          left: 'center'
        },
        tooltip: {
          trigger: 'item'
        },
        legend: {
          orient: 'vertical',
          left: 'left'
        },
        series: [
          {
            name: '品牌',
            type: 'pie',
            radius: '50%',
            data: [],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      },

      predictOption:{
        title: {
          text: '价格预测曲线'
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['LinearPredict', 'ARIMAPredict']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        toolbox: {
          feature: {
            saveAsImage: {}
          }
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: []
        },
        yAxis: {

          type: 'value'
        },
        dataZoom: [
          {
            type: 'inside',
            start: 50,
            end: 100
          },
          {
            start: 50,
            end:100
          }
        ],
        series: [
          {
            name: 'LinearPredict',
            type: 'line',
            data: [],
            lineStyle: {
              type: 'dashed',
              opacity: 0.8,
            }
          },
          {
            name: 'ARIMAPredict',
            type: 'line',
            data: [],
            lineStyle: {
              type: 'dashed',
              dashOffset: 100,
              opacity: 0.8
            }
          }
        ]
      }
    }
  },
  methods: {
    handleLoad () {
      if (this.count <= this.comments.length) {
        this.count += 1
      }
    },
    async fetchPriceHistory() {
      if (this.productId) {
        try {
          const response = await axios.get(`http://127.0.0.1:5000/history_price/${this.productId}`)
          if (response.data.code === 200) {
            this.priceHistory = response.data.data
            this.historyPriceOption.xAxis.data = this.priceHistory.history_prices.map(item => item.date_time)
            this.historyPriceOption.series[0].data = this.priceHistory.history_prices.map(item => item.price)
            this.historyPriceOption.yAxis.min = (this.priceHistory.min_price - 2000) < 0 ? 0 : this.priceHistory.min_price - 2000
            this.historyPriceOption.yAxis.max = this.priceHistory.max_price


            await this.fetchLinearPredict()
            await this.fetchARIMAPredict()
            this.combineLinearData()
            this.combineARIMAData()
          } else {
            console.error('Error fetching price history:', response.data.message)
          }
        } catch (error) {
          console.error('Error fetching price history:', error)
        }
      }
    },

    async fetchPhoneInfo() {
      if (this.productId) {
        try {
          const response = await axios.get(`http://127.0.0.1:5000/phone_info/${this.productId}`)
          if (response.data.code === 200) {
            this.phoneInfo = response.data.data
          } else {
            console.error('Error fetching phone info:', response.data.message)
          }
        } catch (error) {
          console.error('Error fetching phone info:', error)
        }
      }
    },

    async fetchWordData() {
      if (this.productId) {
        try {
          const response = await axios.get(`http://127.0.0.1:5000/word/${this.productId}`)
          if (response.data.code === 200) {
            this.goodWords = response.data.data.good.map(item => ({"name": item.word, "value": item.value}));
            const goodMaxValue = Math.max(...this.goodWords.map(word => word.value));
            this.badWords = response.data.data.bad.map(item => ({"name": item.word, "value": item.value}));
            const badMaxValue = Math.max(...this.badWords.map(word => word.value));
            const scaleFactor = goodMaxValue / badMaxValue;

            this.badWords = this.badWords.map(item => ({
              name: item.name,
              value: item.value * scaleFactor
            }));
          } else {
            console.error('Error fetching word data:', response.data.message)
          }
        } catch (error) {
          console.error('Error fetching word data:', error)
        }
      }
    },

    async fetchEvaluation() {
      if (this.productId) {
        try {
          const response = await axios.get(`http://127.0.0.1:5000/evaluation/${this.productId}`)
          if (response.data.code === 200) {
            this.evaluations = response.data.data
            this.evaluationOption.series[0].data = [
              { value: (this.evaluations.good_rate * 100).toFixed(2), name: '好评'},
              { value: (this.evaluations.medium_rate * 100).toFixed(2), name: '中评'},
              { value: (this.evaluations.bad_rate * 100).toFixed(2), name: '差评'}
            ];
          } else {
            console.error('Error fetching evaluation:', response.data.message)
          }
        } catch (error) {
          console.error('Error fetching evaluation:', error)
        }
      }
    },
    async fetchComment() {
      if (this.productId) {
        try {
          const response = await axios.get(`http://127.0.0.1:5000/comment/${this.productId}`)
          if (response.data.code === 200) {
            this.comments = response.data.data
          } else {
            console.error('Error fetching comments info:', response.data.message)
          }
        } catch (error) {
          console.error('Error fetching comments info:', error)
        }
      }
    },

    async fetchLinearPredict() {
      if (this.productId) {
        try {
          const response = await axios.get(`http://127.0.0.1:5000/predict_linear/${this.productId}`)
          if (response.data.code === 200) {
            this.linearPredict = response.data.data
            console.log(this.linearPredict)
          } else {
            console.error('Error fetching linear predict:', response.data.message)
          }
        } catch (error) {
          console.error('Error fetching linear predict:', error)
        }
      }
    },

    async fetchARIMAPredict() {
      if (this.productId) {
        try {
          const response = await axios.get(`http://127.0.0.1:5000/predict_ARIMA/${this.productId}`)
          if (response.data.code === 200) {
            this.ARIMAPredict = response.data.data
          } else {
            console.error('Error fetching ARIMA predict:', response.data.message)
          }
        } catch (error) {
          console.error('Error fetching ARIMA predict:', error)
        }
      }
    },

    combineLinearData(){
      this.combinedLinearData = Array.from(this.priceHistory.history_prices).concat(Array.from(this.linearPredict))
      console.log('linear', this.combinedLinearData); // 检查拼接后的数组
      this.predictOption.xAxis.data = this.combinedLinearData.map(item => item.date_time);
      this.predictOption.series[0].data = this.combinedLinearData.map(item => item.price)
    },
    combineARIMAData(){
      this.combinedARIMAData = [...this.priceHistory.history_prices,...this.ARIMAPredict];
      console.log('arima', this.combinedARIMAData); // 检查拼接后的数组
      this.predictOption.series[1].data = this.combinedARIMAData.map(item => item.price);
      this.predictOption.yAxis.min = (this.priceHistory.min_price - 2000) < 0 ? 0 : this.priceHistory.min_price - 2000
      this.predictOption.yAxis.max = this.priceHistory.max_price
    }


  },
  mounted() {
    this.fetchWordData()
    this.fetchPriceHistory()
    this.fetchPhoneInfo()
    this.fetchEvaluation()
    this.fetchComment()
  },


  components: {
    VChart,
    WordCloud,
    NInfiniteScroll
  },
}
</script>

<template>
  <div class="product-detail-container">
    <header>
      <h2 v-if="phoneInfo">{{ phoneInfo.title }}</h2>
      <p>ID: {{ productId }}</p>
    </header>

    <main>
      <div class="info-eva">
        <section class="info-section">
          <h1>手机配置</h1>
          <div v-if="phoneInfo" class="info-list">
          <ul>
            <li><strong>品牌:</strong> {{ phoneInfo.brand }}</li>
            <li><strong>后摄主像素:</strong> {{ phoneInfo.camera_pixel }}</li>
            <li><strong>充电功率:</strong> {{ phoneInfo.charge_power }}</li>
            <li><strong>机身颜色:</strong> {{ phoneInfo.colour }}</li>
            <li><strong>色系:</strong> {{ phoneInfo.colour_scheme }}</li>
            <li><strong>CPU型号: </strong>{{ phoneInfo.cpu }}</li>
            <li><strong>机身内存:</strong> {{ phoneInfo.internal_storage }}</li>
            <li><strong>支持IPv6:</strong> {{ phoneInfo.ipv6 ? '支持' : '不支持' }}</li>
            <li><strong>商品名称: </strong>{{ phoneInfo.product_name }}</li>
            <li><strong>排名：</strong> {{ phoneInfo.rank }}</li>
            <li><strong>运行内存:</strong> {{ phoneInfo.running_memory }}</li>
            <li><strong>屏幕材质:</strong> {{ phoneInfo.screen_material }}</li>
            <li><strong>屏幕分辨率:</strong> {{ phoneInfo.screen_resolution }}</li>
            <li><strong>三防标准:</strong> {{ phoneInfo.th_p_standards }}</li>
          </ul>
        </div>
        </section>

        <section v-if="evaluations">
          <h2>评价占比</h2>
          <ul>
            <v-chart class="Evaluation" :option="evaluationOption"></v-chart>
          </ul>
        </section>
      </div>

      <section class="word-clouds">
        <h2>词云图</h2>
        <div class="word-cloud-container">
          <div v-if="goodWords.length" class="word-cloud">
            <h3>好评词云图</h3>
            <WordCloud :data="goodWords" type="good" />
          </div>
          <div v-if="badWords.length" class="word-cloud">
            <h3>中差评词云图</h3>
            <WordCloud :data="badWords" type="bad" />
          </div>
        </div>
      </section>
      <div class="comments-container">
        <h2>评论情感分析</h2>
        <n-infinite-scroll style="height: 400px" :distance="10" @load="handleLoad">
          <div v-for="comment in comments" :key="comment" class="item">
        <span class="score">
          评分：{{ comment.score }}
          <span v-if="comment.emotion < 0.4" class="emo-neg">
            Neg
          </span>
          <span v-if="comment.emotion >= 0.4 && comment.emotion <= 0.6" class="emo-mid">
            Mid
          </span>
          <span v-if="comment.emotion >0.6" class="emo-pos">
            Pos
          </span>
        </span>
            <span class="user-comment">
          {{ comment.user_comment }}
        </span>
          </div>
        </n-infinite-scroll>
      </div>


      <section class="chart-section">
        <h2>价格趋势图</h2>
        <v-chart class="price-history-chart" :option="historyPriceOption" />
        <v-chart class="price-history-chart" :option="predictOption" />
      </section>

    </main>


  </div>
</template>

<style scoped>
.product-detail-container {
  max-width: 1200px;
  margin: 0 auto;
}

header {
  text-align: center;
  padding: 2rem 0;
}

.info-eva {
  display: flex;
  justify-content: space-between;
}

.info-section,
.chart-section,
.word-clouds {
  margin-bottom: 3rem;
}

h2 {
  margin-top: 2rem;
}

.info-list ul {
  width: 450px;
  list-style: none;
  padding: 0;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;

}

.info-list li {
  width: 200px;
  margin-bottom: 1rem;
}

.Evaluation{
  width: 500px;
  height: 300px;
}

.price-history-chart {
  height: 400px;
  width: 100%;
}

.word-cloud-container {
  display: flex;
  justify-content: space-between; /* To create space between the two word clouds */
}
.word-cloud {
  flex: 1; /* Each word cloud will take up an equal amount of space */
  margin: 10px; /* Optional: add some margin for better spacing */
}
.word-clouds h3 {
  margin-top: 1.5rem;
}
.item {
  display: flex;
  align-items: center;
  height: 100%;
  justify-content: center;
  margin-bottom: 10px;
  background-color: rgba(0, 128, 0, 0.16);
}

.item:last-child {
  margin-bottom: 0;
}

.comments-container {
  width: 100%;
  max-width: 100%;
  margin: 0 auto;
  padding: 10px;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.item {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 10px;
  margin-bottom: 10px;
  background-color: #fff;
  border-radius: 6px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s ease-in-out;
}

.item:hover {
  transform: scale(1.02);
}

.score,
.user-comment {
  font-size: 16px;
  color: #333;
  margin-bottom: 4px;
}

.score {
  font-weight: bold;
  color: #ff9800;
}

.emo-pos {
  font-weight: bold;
  color: #09ef18;
}

.emo-neg {
  font-weight: bold;
  color: #ea0707;
}

.emo-mid {
  font-weight: bold;
  color: #f1e908;
}

.user-comment {
  color: #666;
}


</style>
